$(document).ready(function () {
    initMap();

    $('input[name="size"][value="0.9"]').prop('checked', true);
})


var map = null, satellite = null;//地图相关实例
var loca = null;//可视化图层实例
var mouseTool = null;//鼠标工具类
var curHue = 0;//自定义图标颜色

var cluster, gridSize = 50;//点聚合

var OverlayGroups = {//覆盖物群组
    street: null,//街道
    area: null,//区域
    bound: null,//边界
}

var FireGroups = {//火警资源群组
    fire: null,//火情
    "微型消防站": null,
    "快速处置队": null,
    "消火栓": null,
    "天然水源": null,
    "单点单位": null,
    "风险点": null,
}


var MouseDrawGroups = [];//绘制的覆盖物


var sName = [];//存放街道标注信息

var streetList = {
    "宝临食品厂": {
        "name": "宝临食品厂",
        'coordinates': [115.306099, 33.037220],
        "color": "rgb(0, 119, 255)",
        "icon": "宝临食品厂.png"
    }
}

// 初始化地图
initMap = () => {

    map = new AMap.Map('mapContainer', {
        WebGLParams: {
            preserveDrawingBuffer: true //截图必须开启
        },
        zoom: 15.2,
        pitch: 55,
        rotation: 41,
        center: [115.28622881070024, 33.03721493370621],
        features: ['bg', 'road', 'building'],
        resizeEnable: true,
        viewMode: '3D', //开启3D视图,默认为关闭
        mapStyle: 'amap://styles/dark',// normal,dark,light,whitesmoke,fresh,grey,graffiti,macaron,blue,darkblue,wine

    });


    // 卫星图层
    satellite = new AMap.TileLayer.Satellite({
        map: map,
    });
    satellite.setMap(map);
    satellite.hide();

    // 可视化图层
    loca = window.loca = new Loca.Container({
        map,
    });


    drawQXBoundary()
    drawCircles()
    drawCountRanking()

    // 工具类
    mouseTool = new AMap.MouseTool(map);

    //监听draw事件可获取画好的覆盖物
    mouseTool.on('draw', function (e) {
        MouseDrawGroups.push(e.obj);
    })

    map.on('click', function (e) {
        console.log(e);

    });

    map.on('zoomchange', function (e) {
        if (map.getZoom() < 15) {
            $('.marker-text').hide();
        } else {
            $('.marker-text').show();
        }

    });

}
// 切换地图类型
$('.layers-switch').click(function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active');
    if ($(e.currentTarget).data().type == 1) {
        satellite.hide();
        map.setMapStyle('amap://styles/whitesmoke')
    } else if ($(e.currentTarget).data().type == 2) {
        satellite.show();
    } else {
        satellite.hide();
        map.setMapStyle('amap://styles/dark')
    }
})




drawQXBoundary = () => {
    ajax('../static/栖霞区.json', function (err, geoJSON) {
        if (!err) {
            var geojson = new AMap.GeoJSON({
                geoJSON: geoJSON,
                getPolygon: function (geojson, lnglats) {
                    var polygon = new AMap.Polygon({
                        path: lnglats,
                        fillOpacity: 0.5,
                        strokeWeight: 2,
                        strokeColor: 'rgba(41, 141, 141, 1)',
                        fillColor: 'rgba(165, 241, 247, 1)',
                    });

                    polygon.name = geojson.properties.name;

                    polygon.on('click', function (e) {
                        map.setFitView(this);
                    });

                    return polygon
                },
            });


            OverlayGroups['area'] = geojson
            map.add(OverlayGroups['area']);
            // map.setFitView();
            log.success('GeoJSON 数据加载完成')
        } else {
            log.error('GeoJSON 服务请求失败')
        }
    })
    // 街道名称
    for (var key in streetList) {
        sName.push({
            "icon": streetList[key].icon,
            "name": streetList[key].name,
            "longitude": streetList[key].coordinates[0],
            "latitude": streetList[key].coordinates[1]
        });
    }
    drawIconToMap(sName, 'street', 1);
    drawHotMapIconToMap()
}

// 处理GeoJSON数据
function processGeoJSON(geojson) {

    // 遍历所有特征
    geojson.features.forEach(function (feature) {
        var geometry = feature.geometry;

        geometry.coordinates.forEach(function (multiPolygon) {
            var polygon = multiPolygon[0];
            // 提取外环路径
            var path = polygon.map(function (coord) {
                return [coord[0], coord[1]];
            });

            createAnimatedLine(path);
        });
    });
}

// 创建动态边界线
function createAnimatedLine(path) {

    let len = Math.floor(path.length * 0.8);

    let polyline = new AMap.Polyline({
        path: path,
        strokeWeight: 5,
        strokeColor: '#000000',
        strokeOpacity: 1
    });
    OverlayGroups['bound'] = polyline
    map.add(OverlayGroups['bound']);
    new TWEEN.Tween({ start: 0 })
        .to({ start: path.length }, 50000)
        .repeat(Infinity)         // 无限循环
        .onUpdate(function (obj) {

            if (obj.start + len < path.length) {
                polyline.setPath(path.slice(obj.start, obj.start + len));
            } else {
                const c = path.length - obj.start;
                //头尾相接时截取尾部+头部各一段
                polyline.setPath(
                    [].concat(path.slice(obj.start, path.length), path.slice(0, len - c))
                );
            }
        })
        .start();
}

// 动画循环
function animate() {
    requestAnimationFrame(animate);
    TWEEN.update();
}


// 绘制初始加载热力圆点
drawHotMapIconToMap = () => {
    $('.load-box').css(
        'display', 'flex'
    )

    $('.load-box').fadeOut(200);



    return

    Ajax('/data/map/situation/show', callback,
        {
            "resid": 1,
            "areaCode": null,
            "policeType": null,
            "fireSite": null
        }
        , 'post');
    function callback(res) {

        if (res.message == "OK") {

            var geo = new Loca.GeoJSONSource({
                data: res.result
            });


            var pl = window.pl = new Loca.PointLayer({
                zIndex: 10,
                blend: 'lighter',
            });

            var style = {
                radius: 3.5,
                unit: 'px',
                color: '#f11515',
                borderWidth: 0,
                blurWidth: 3.5,
            }
            pl.setSource(geo);
            pl.setStyle(style);
            loca.add(pl);

            pl.addAnimate({
                key: 'radius',
                value: [0, 1],
                duration: 500,
                easing: 'Linear',
                transform: 2000,
                random: true,
                delay: 8000,
                yoyo: true,
                repeat: 100000
            });

            $('.load-box').fadeOut();

        } else {
        }

    }

}


/**
 * 方法描述：绘制地图图标
 * @function drawIconToMap
 * @param {[]} data - 数据源
 * @param {string} groupName - 图层群组名称,分组用
 * @param {string} type - 1:普通资源 2:火警 3:资源点
 * @returns
*/

function drawIconToMap(data, groupName, type) {

    var markers = [];
    for (var i = 0; i < data.length; i++) {
        // 创建点实例
        var marker = new AMap.Marker({
            zooms: [5, 20],
            position: new AMap.LngLat(data[i].longitude, data[i].latitude),
            anchor: 'center',
            content: `<img class="${type == 2 ? 'fire-marker' : ''}" src="../static/img/oneMap/${data[i].icon}">`,
            offset: new AMap.Pixel(-10, -25),
            extData: {
                id: i + 1,
                ...data[i]
            }
        });

        if (data[i].icon == "配送车.png") {
            let color = "";
            if (data[i].temp > 4) {
                color = 'color:rgb(238, 16, 5)'
            }
            var content =
                `<img class="cluster-icon" src="../static/img/oneMap/${data[i].icon}">
                 <p class="marker-text" style="${color}">${data[i].name}</p>
                 <p class="marker-text" style="${color}">车厢温度：${data[i].temp}℃</p>`;
            marker.setContent(content);
            marker.on('click', function (e) {
                queryStreet(e.target.getExtData());
            });
        }

        if (data[i].icon == "配送终点.png") {
            var content =
                `<img class="cluster-icon" src="../static/img/oneMap/${data[i].icon}">
                 <p class="marker-text" style="color: #eee;margin-left: -0.5rem;">${data[i].name}</p>`;
            marker.setContent(content);
            marker.on('click', function (e) {
                getRoute({ lat: e.target.getExtData().latitude, lng: e.target.getExtData().longitude })
            });
        }


        if (data[i].name == "宝临食品厂") {

            marker.on('click', function (e) {
                positioningToFire(e.target.getExtData().longitude, e.target.getExtData().latitude);

            });
        }

        markers.push(marker);
    }

    if (type != 1) {
        if (type == 2) {
            // 火灾标注
            markers.push(new AMap.Marker(
                {
                    zooms: [12, 15],
                    anchor: 'bottom-left',
                    position: new AMap.LngLat(data[0].longitude, data[0].latitude),
                    offset: new AMap.Pixel(50, -50),
                    content: `<div class="fire-marker-label">
                        <div class="close-marker-label" onclick="closeFireMarker()">×</div>
                       <p>中国石化销售有限公司江苏南京石油分公司栖霞油库（甘家巷）于2025-07-15 12:12:14监测到火警异常</p>
                      </div>`,
                }
            ));
        }

        FireGroups[groupName] = new AMap.OverlayGroup(markers)
        map.add(FireGroups[groupName]);

    } else {
        OverlayGroups[groupName] = new AMap.OverlayGroup(markers)
        map.add(OverlayGroups[groupName]);
    }

}

function closeFireMarker() {
    $('.fire-marker-label').hide();
}



// 切换图标大小
$("input[type='radio']").change(function () {
    var size = $(this).val();
    $('.amap-marker').css('scale', size)
});


// 显隐覆盖物群组
function OverlayBlock(groups, type) {

    Object.keys(groups).forEach(key => {
        type ? groups[key]?.hide() : groups[key]?.show()
    })
}


// 点击左侧资源按钮控制地图资源
$('.map-s-item').on('click', function () {

    let key = $(this).data().type;

    if (!$(this).hasClass('active')) {

        FireGroups[key].show();

    } else {
        FireGroups[key].hide();
    }
    $(this).toggleClass('active');
});





// 定位至车辆
function positioningToFire(lng, lat) {
    map.setZoomAndCenter(16, [lng, lat], false, 500);



}


// 绘制等时圆

function drawCircles() {

    var geoLevelF = new Loca.GeoJSONSource({
        data: {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [
                            115.306099, 33.037220
                        ]
                    },
                    "properties": {
                        "name": "测试",
                        "value": 116.7527076,
                        "level": "F",
                        "month": 202005
                    }
                }
            ]
        },
        // url: '../static/test.json',
    });


    for (let i = 0; i < 3; i++) {

        var breath = new Loca.ScatterLayer({
            loca,
            zIndex: 113,
            opacity: 0.6 - 0.2 * i,
            visible: true,
            zooms: [2, 15],
            blend: 'lighter'
        });
        breath.setSource(geoLevelF);
        breath.setStyle({
            unit: 'meter',
            size: [[7, 14, 40][i] * 2000, [7, 14, 40][i] * 2000],
            borderWidth: 1,
            texture: '../static/img/index/icon' + i + '.png',
        });
    }


    var groupedData = {
        "客户": [
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县阜临小学",
                "longitude": 115.261758,
                "latitude": 33.067454,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县幸福路小学",
                "longitude": 115.266746,
                "latitude": 33.033932,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县城中路小学",
                "longitude": 115.254792,
                "latitude": 33.038926,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县智慧小学",
                "longitude": 115.258807,
                "latitude": 33.067714,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县顺河街小学",
                "longitude": 115.260110,
                "latitude": 33.070606,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县城南小学",
                "longitude": 115.261557,
                "latitude": 33.049942,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县鸿辉小学",
                "longitude": 115.261678,
                "latitude": 33.042398,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县临泉县前进小学",
                "longitude": 115.266711,
                "latitude": 33.058179,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县新建路小学",
                "longitude": 115.276376,
                "latitude": 33.058591,
            },
            {
                "icon": "配送终点.png",
                "name": "阜阳市临泉县高集村小学",
                "longitude": 115.376489,
                "latitude": 32.692888,
            }

        ]
    }

    var carData = {
        "配送车": [
            {
                "icon": "配送车.png",
                "name": "皖K0C867",
                "status": 1,
                "longitude": 115.274928,
                "latitude": 33.041224,
                "temp": 3.6
            },
            {
                "icon": "配送车.png",
                "name": "皖K16Z55",
                "status": 1,
                "longitude": 115.276946,
                "latitude": 33.052366,
                "temp": 1.6
            },
            {
                "icon": "配送车.png",
                "name": "皖K99R96",
                "status": 1,
                "longitude": 115.266469,
                "latitude": 33.052724,
                "temp": 0.6
            },
            {
                "icon": "配送车.png",
                "name": "皖K303A3",
                "status": 1,
                "longitude": 115.265411,
                "latitude": 33.046922,
                "temp": 3.1
            },
            {
                "icon": "配送车.png",
                "name": "皖K335V7",
                "status": 1,
                "longitude": 115.267588,
                "latitude": 33.041053,
                "temp": 4.9
            },
            {
                "icon": "配送车.png",
                "name": "皖K8226R",
                "status": 1,
                "longitude": 115.269017,
                "latitude": 33.037560,
                "temp": 2.8
            },
            {
                "icon": "配送车.png",
                "name": "皖K83680",
                "status": 1,
                "longitude": 115.267017,
                "latitude": 33.041922,
                "temp": 2.7
            },
            {
                "icon": "配送车.png",
                "name": "皖KD0X16",
                "status": 1,
                "longitude": 115.264017,
                "latitude": 33.039922,
                "temp": 2.3
            },
            {
                "icon": "配送车.png",
                "name": "皖KD1C06",
                "status": 1,
                "longitude": 115.266017,
                "latitude": 33.049922,
                "temp": 2.5
            },
            {
                "icon": "配送车.png",
                "name": "皖K8363K",
                "status": 1,
                "longitude": 115.274651,
                "latitude": 33.062598,
                "temp": 1.9
            },
            {
                "icon": "配送车.png",
                "name": "皖KF2W06",
                "status": 1,
                "longitude": 115.257639,
                "latitude": 33.054832,
                "temp": 2.3
            },
            {
                "icon": "配送车.png",
                "name": "皖KFD988",
                "status": 1,
                "longitude": 115.290225,
                "latitude": 33.081479,
                "temp": 2.6
            },
            {
                "icon": "配送车.png",
                "name": "皖KK5L78",
                "status": 1,
                "longitude": 115.296302,
                "latitude": 33.029157,
                "temp": 2.7
            },
            {
                "icon": "配送车.png",
                "name": "皖KLV656",
                "status": 1,
                "longitude": 115.292076,
                "latitude": 33.056132,
                "temp": 4.2
            },
            {
                "icon": "配送车.png",
                "name": "皖KM1P22",
                "status": 1,
                "longitude": 115.282776,
                "latitude": 33.049481,
                "temp": 3.9
            },
            {
                "icon": "配送车.png",
                "name": "皖KM5181",
                "status": 0,
                "longitude": 115.27473,
                "latitude": 33.03111,
                "temp": 3.9
            },
            {
                "icon": "配送车.png",
                "name": "皖KRT578",
                "status": 0,
                "longitude": 115.286658,
                "latitude": 33.029176,
                "temp": 2.2
            },
            {
                "icon": "配送车.png",
                "name": "皖KS2268",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 2.2
            },
            {
                "icon": "配送车.png",
                "name": "皖KS6717",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },
            {
                "icon": "配送车.png",
                "name": "皖KDH8677",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },
            {
                "icon": "配送车.png",
                "name": "皖KDP8063",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },
            {
                "icon": "配送车.png",
                "name": "皖KQF216",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },
            {
                "icon": "配送车.png",
                "name": "皖KQM357",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },
            {
                "icon": "配送车.png",
                "name": "皖KCX356",
                "status": 0,
                "longitude": 115.306838,
                "latitude": 33.035674,
                "temp": 1.8
            },


        ]
    }


    $.each(groupedData, function (key, val) {

        drawIconToMap(val, key, 3);

    });
    $.each(carData, function (key, val) {

        drawIconToMap(val.filter(item => item.status != 0), key, 3);

    });

    queryCarList(carData['配送车'])



}


function queryCarList(res) {

    var data = res.filter(item => item.status != 0);


    $('.map-car').empty()
        .append(data.reduce((x, y, i) => {

            let color = "rgb(0, 255, 64)";
            if (y.temp > 4) {
                color = 'rgb(238, 16, 5)'
            }
            if (i < 9) {

                return x + `<div class="map-s-item"   onclick="positioningToFire(${y.longitude},${y.latitude})">
                    ${y.name}<span style="color: ${color};">${y.temp}℃</span>
                </div>`

            } else if (i == 9) {

                return x + `<div class="map-s-item" id="car-dropdown">
                                更多
                            </div>`
            } else {
                return x
            }

        }, ''))


    layui.use(function () {

        var dropdown = layui.dropdown;

        // 渲染

        dropdown.render({

            elem: '#car-dropdown',

            data: res.slice(9),
            customName: {
                title: 'name',
            },
            templet: function (d) {
                let color = "rgba(12, 197, 58, 1)";
                if (d.temp > 4) {
                    color = 'rgb(238, 16, 5)'
                }

                if (d.status == 0) {
                    return `<div style="color: #999;"><span >离线中</span>
                    ${d.name}
                </div>`
                } else {
                    return `<div>
                    ${d.name}<span style="color: ${color};"> ${d.temp}℃</span>
                </div>`
                }

            },
            click: function (obj) {

                if (obj.status == 1) {
                    positioningToFire(obj.longitude, obj.latitude)
                }
            }

        });



    });

}



// 获取驾驶路线

function getRoute(poi) {
    $('#close-map-window').click()
    //构造路线导航类

    var driving = new AMap.Driving({
        map: map,
        panel: "panel"
    });
    // 根据起终点经纬度规划驾车导航路线
    driving.search(new AMap.LngLat(115.305865, 33.035743), new AMap.LngLat(poi.lng, poi.lat), function (status, result) {
        if (status === 'complete') {
            log.success('绘制驾车路线完成')
            $('.panel').show();

            AMap.plugin('AMap.MoveAnimation', function () {
                var marker, lineArr = [];

                result.routes[0].steps.forEach(e => {

                    e.tmcs.forEach(item => {

                        lineArr.push({
                            position: new AMap.LngLat(item.polyline.split(';')[1].split(',')[0], item.polyline.split(';')[1].split(',')[1]),
                            duration: item.distance * 1
                        })

                    });
                });

                marker = new AMap.Marker({
                    map: map,
                    position: [poi.lng, poi.lat],
                    content: `<img class="car-marker" src="../static/img/oneMap/car.png">`,
                    offset: new AMap.Pixel(-13, -26),
                });

                map.setZoom(14.9)

                marker.on('moving', function (e) {
                    map.setCenter(e.target.getPosition(), true)
                });

                marker.moveAlong(lineArr, {
                    autoRotation: true,
                });
            });
        } else {
            log.error('获取驾车数据失败：' + result)
        }

    });
}


// 计算两点的距离
function computeDis(polyline) {
    var p1 = new AMap.LngLat(polyline.split(';')[0].split(',')[0], polyline.split(';')[0].split(',')[1]);
    var p2 = new AMap.LngLat(polyline.split(';')[1].split(',')[0], polyline.split(';')[1].split(',')[1]);
    var distance = Math.round(p1.distance(p2));
    return distance
}


$('.map-tool-item').on('click', function () {

    mouseTool.close(false);//关闭绘制功能，但是保留绘制物
    $('.map-tool-config').hide();

    if (!$(this).hasClass('active')) {
        $(this).addClass('active').siblings().removeClass('active');
        toolDraw($(this).data().value);
    } else {
        $(this).removeClass('active');

    }
});

/**
 * 地图工具事件
 * @function toolDraw
 * @param {int} type - 工具类型
 * @returns {类型} 返回值描述
*/

function toolDraw(type) {

    switch (type) {
        case 'marker': {//地图标注

            curHue = 0;
            $('.map-tool-config').empty().append($('#map-tool').html()).show();

            markerTool();

            // 监听用户输入自定义标注
            $('#silder-value').on('change', function () {
                markerTool()
            });

            // 监听滑块改变颜色

            layui.use(function () {
                var slider = layui.slider;
                slider.render({
                    elem: '#silder',
                    theme: '#06fcfc',
                    tips: false,
                    max: 320,
                    step: 40,
                    showstep: true, // 开启间隔点
                    change: function (value) {
                        $('.silder-icon').css('filter', 'hue-rotate(' + value + 'deg)')
                    },
                    done: function (value) {
                        curHue = value;
                        markerTool()
                    }
                });

            });
            break;
        }
        case 'rule': {//距离测量
            mouseTool.rule({
                startMarkerOptions: {//起点
                    icon: new AMap.Icon({
                        size: new AMap.Size(19, 40),
                        imageSize: new AMap.Size(19, 40),
                        image: "../static/img/index/i6.png"
                    }),
                    offset: new AMap.Pixel(-19, -40)
                },
                endMarkerOptions: {//途经点
                    icon: new AMap.Icon({
                        size: new AMap.Size(19, 40),
                        imageSize: new AMap.Size(19, 40),
                        image: "../static/img/index/i8.png"
                    }),
                    offset: new AMap.Pixel(-19, -40)
                },
                midMarkerOptions: {//终点
                    icon: new AMap.Icon({
                        size: new AMap.Size(19, 40),
                        imageSize: new AMap.Size(19, 40),
                        image: "../static/img/index/i7.png"
                    }),
                    offset: new AMap.Pixel(-19, -40)
                },
                lineOptions: {
                    strokeStyle: "dashed",
                    strokeColor: "#fc9724",
                    strokeOpacity: 1,
                    strokeWeight: 2,
                }
            });
            break;
        }
        case 'area': {//面积测量
            mouseTool.measureArea({
                fillColor: '#eaec44',
                fillOpacity: 0.1,
                strokeStyle: "dashed",
                strokeColor: "#f8fc24",
                strokeOpacity: 0.5,
                strokeWeight: 1,
            });
            break;
        }
        case 'polyline': {//路径绘制
            mouseTool.polyline({
                strokeColor: '#80d8ff',
                strokeWeight: 1,
            });
            break;
        }
        case 'polygon': {//多边形绘制
            mouseTool.polygon({
                fillColor: '#7bff00',
                fillOpacity: 0.1,
                strokeColor: '#80ffa0',
                strokeOpacity: 0.5,
                strokeWeight: 1,
            });
            break;
        }
        case 'circle': {//圆形绘制
            mouseTool.circle({
                fillColor: '#2f00ff',
                fillOpacity: 0.1,
                strokeColor: '#80d8ff',
                strokeOpacity: 0.5,
                strokeWeight: 1,
            });
            break;
        }
        case 'clear': {//清除绘制
            map.remove(MouseDrawGroups)
            MouseDrawGroups = [];
            break;
        }
        case 'screenshot': {//屏幕截图
            screenshot()
            break;
        }
        case 'init': {//初始化
            map && map.destroy();
            initMap();

            $('#panel').html("");
            $('.panel').hide();
            break;
        }
        default:

            break;
    }
}


// 注册地图标注事件
function markerTool() {

    mouseTool.marker({
        content: `<div style="position: relative;filter:hue-rotate(${curHue}deg);">
                            <img src="../static/img/index/i4.png">
                            <span class="map-silder-icon">${$('#silder-value').val()}</span>
                        </div>`,
        offset: new AMap.Pixel(-27, -36),
    });
}

// 弹出车辆详情
queryStreet = (res) => {

    if (res.temp > 4) {
        $(".top-temp").html('<span style="color: rgb(238, 16, 5);">温度过高</span>')
    } else {
        $(".top-temp").html('<span style="color: #11ffd7;">正常</span>')
    }

    $('.map-window').css('display', 'flex')
    $('#map-title').html(res.name + ' 车辆看板')
    drawEventTrend("window-trend", 1)
    drawEventTrend("overviewChart", 2)
    casualtiesListChart()

}

// 关闭车辆弹窗
$('#close-map-window').click(function () {
    $('.map-window').hide()
})


// 事件趋势

drawEventTrend = (id, type) => {


    switch (type) {
        case 1://温度

            var list = [
                {
                    "key": "2025-01",
                    "name": null,
                    "value": 1.9
                },
                {
                    "key": "2025-02",
                    "name": null,
                    "value": 1.2
                },
                {
                    "key": "2025-03",
                    "name": null,
                    "value": 1.1
                },
                {
                    "key": "2025-04",
                    "name": null,
                    "value": 1.4
                },
                {
                    "key": "2025-05",
                    "name": null,
                    "value": 1.5
                },
                {
                    "key": "2025-06",
                    "name": null,
                    "value": 1
                },
                {
                    "key": "2025-07",
                    "name": null,
                    "value": 1.4
                },
                {
                    "key": "2025-08",
                    "name": null,
                    "value": 2.5
                },
                {
                    "key": "2025-09",
                    "name": null,
                    "value": 1.6
                },
                {
                    "key": "2025-10",
                    "name": null,
                    "value": 1.6
                },
                {
                    "key": "2025-11",
                    "name": null,
                    "value": 1.6
                },
                {
                    "key": "2025-12",
                    "name": null,
                    "value": 1.8
                }
            ]


            var title = '温度';
            var colors = ['rgba(82, 215, 255, 1)', 'rgba(79, 190, 255, 1)',
                'rgba(84, 187, 255, 0.5)',
                'rgba(79, 161, 255, 0.1)']
            break;
        case 2://超时

            var list = [
                {
                    "key": "01",
                    "value": 5
                },
                {
                    "key": "02",
                    "value": 4
                },
                {
                    "key": "03",
                    "value": 6
                },
                {
                    "key": "04",
                    "value": 4
                },
                {
                    "key": "05",
                    "value": 5
                },
                {
                    "key": "06",
                    "value": 2
                },
                {
                    "key": "07",
                    "value": 7
                },

            ]


            var title = '次数';
            var colors = ['rgba(242, 193, 33, 1)', 'rgba(255, 93, 93,1)',
                'rgba(211, 242, 33, 0.5)',
                'rgba(231, 255, 93, 0.1)']
            break;

        default:
            break;
    }

    let xData = [], yData = [];
    list.forEach((item, i) => {


        xData.push(item.key.substring(5))

        if ((i - 1) < (new Date().getMonth())) {
            yData.push(item.value)
        } else {
            yData.push(null)
        }

    });


    var option = {
        tooltip: {
            trigger: 'axis'
        },

        grid: { left: '14%', top: 10, bottom: 20, right: 15, containLabel: false },
        xAxis: {
            type: 'category',
            data: xData,
            axisLine: { show: false },
            axisLabel: { color: '#99A4B7' },
            axisTick: { show: false },
            splitLine: {
                show: false,
            },
        },
        yAxis: {
            type: 'value',
            minInterval: 1,
            axisLine: { show: false },
            axisLabel: { color: '#99A4B7' },
            axisTick: { show: false },
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dashed',
                    color: "rgba(255,255,255,0.1)",
                    dashOffset: 1
                }
            },
        },
        series: [

            {
                name: title,
                type: 'line',
                data: yData,
                symbol: 'none',
                markPoint: {
                    symbolSize: '29',
                    symbol: 'image://',
                    label: {
                        show: false
                    },
                    data: [{
                        type: 'max',
                        name: '最大值',
                    },
                    ]
                },
                itemStyle: {
                    normal: {
                        borderWidth: 3,
                        //4个参数用于配置渐变色的起止位置, 这4个参数依次对应右/下/左/上四个方位
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            1,
                            0,
                            [{
                                offset: 0,
                                color: colors[0]
                            },
                            {
                                offset: 1,
                                color: colors[1]
                            }
                            ]
                        )
                    }
                },
                areaStyle: {
                    normal: {
                        origin: 'start',
                        color: new echarts.graphic.LinearGradient(
                            1, 0, 0, 0,
                            [
                                {
                                    offset: 0,
                                    color: colors[2]
                                },
                                {
                                    offset: 1,
                                    color: colors[3]
                                }
                            ]
                        )
                    }
                }
            },
        ],
    };


    var chart = echarts.init(document.getElementById(id));
    chart.setOption(option)
}
// 配送排行
drawCountRanking = () => {

    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'none',
            },
            formatter: function (params) {
                return params[0].name + ' : ' + params[0].value;
            },
        },
        xAxis: {
            show: false,
            type: 'value',
            axisLabel: {
                show: true,
                interval: 0,
            }
        },
        grid: {
            right: '20%',
            left: '30%',
            top: '5%',
            bottom: '4%',
        },
        yAxis: [
            {
                type: 'category',
                inverse: true,
                offset: 60,
                axisLabel: {
                    show: true,
                    interval: 0,
                    align: 'left',
                    textStyle: {
                        color: '#eee',
                    },

                },
                splitLine: {
                    show: false,
                },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                },
                data: ['幸福路小学',
                    '城中路小学',
                    '智慧小学',
                    '顺河街小学',
                    '城南小学',
                    '新建路小学'],
            },
            {
                type: 'category',
                inverse: true,
                offset: 0,
                axisTick: 'none',
                axisLine: 'none',
                show: true,
                axisLabel: {
                    textStyle: {
                        color: '#37cbf0',
                    },
                },
                data: [27, 25, 23, 21, 19, 15]
            },
        ],
        series: [
            {
                name: '值',
                type: 'bar',
                zlevel: 1,
                itemStyle: {
                    normal: {
                        // barBorderRadius: 30,
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 1,
                            y2: 0,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: 'rgba(40, 66, 87, 0.5)', //  0%  处的颜色
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(91, 233, 241, 1)', //  100%  处的颜色
                                },
                            ],
                            global: false, //  缺省为  false
                        },
                    },
                },
                barWidth: 3,
                barBorderRadius: [0, 7, 7, 0],
                data: [27, 25, 23, 21, 19, 15],
            },
            {
                name: '背景',
                type: 'bar',
                barWidth: 3,
                barGap: '-100%',
                data: [27, 27, 27, 27, 27, 27],
                itemStyle: {
                    color: '#2D4D67',
                    // barBorderRadius: 30,
                },
            },
        ],
    };

    var chart = echarts.init(document.getElementById('count-ranking'));
    chart.setOption(option)

}





//  今日配送订单
var testData = [
    { "orderId": "BL250915336", "status": 2, "name": '幸福路小学', "details": "牛腱子20kg" },
    { "orderId": "BL250915337", "status": 2, "name": '城中路小学', "details": "牛大骨10KG,牛奶30KG" },
    { "orderId": "BL250915338", "status": 1, "name": '智慧小学', "details": "牛腿肉10KG，牛腱子16KG" },
    { "orderId": "BL250915339", "status": 0, "name": '顺河街小学', "details": "牛腩15KG,牛骨10KG" },
    { "orderId": "BL250915340", "status": 0, "name": '城南小学', "details": "牛杂24KLG" },
    { "orderId": "BL250915341", "status": 0, "name": '新建路小学', "details": "牛腱子20kg," },
]

casualtiesListChart = () => {


    var data = testData.slice(0, 5);

    var statusDom = ''


    $('#casualtiesListChart').empty().append(data.reduce((x, y, i) => {
        if (y.status == 2) {
            statusDom = `<span style="color: #29ebff;">已完成</span>`
        } else if (y.status == 1) {
            statusDom = `<span style="color: #ffae14;">配送中</span>`
        } else if (y.status == 0) {
            statusDom = `<span style="color: #aaaaaa;">待配送</span>`
        }

        return x + `
                <div class="street-list" style="height:${80 / data.length}%">
                    <div>${statusDom}</div>
                    <div>${y.orderId}</div>
                    <div>${y.name}</div>
                    <div>${y.details}</div>
                </div>
                `
    }, `<div class="street-list" style="height:20%">
                    <div>状态</div>
                    <div>订单编号</div>
                    <div>客户名称</div>
                    <div>明细</div>
                </div>`))
}
